package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.FillingCardRechargeService;
import com.gljx.web.service.FillingCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class FillingCardRechargeController {
	
	
	// 自动注入
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private CustomLogService customLogService;
	
	@Autowired
	private FillingCardRechargeService fillingCardRechargeService;
	
	//自动注入
	@Autowired
	private FillingCardService fillingCardService;

	//自定义流程工具
	private Axamine axamine = new Axamine();

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();
	
	/**
	 * 查找加油卡充值信息
	 * @param request
	 * @param fnumber
	 * @param fdescription
	 * @param beginTime
	 * @param endTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/queryFillingCardRecharge/look.action")
	public String selFillingCardRecharge(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "fdescription", defaultValue = "") String fdescription          
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "")String endTime
			,@RequestParam(value = "type",defaultValue = "") String type
			, @RequestParam(value = "selectState",required = false,defaultValue = "-1") String selectState)throws Exception{
		PageBean<FillingCardRecharge> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格         
            beginTime=beginTime.trim();
            endTime=endTime.trim();
            fdescription=fdescription.trim();
			if("1".equals(selectState)){//如果传过来的标记为1 所以业务日期为空默认查询全部
				pb=getPageBean(request,user.getFcompanyid(),fnumber,fdescription,null,null);
			}else{
				//默认时间
				if ("".equals(beginTime) && "".equals(endTime)) {
					beginTime = TimeFormat.getMonth();
					endTime = TimeFormat.getNowTime();
				}
				//获取分页
				pb=getPageBean(request,user.getFcompanyid(),fnumber,fdescription,beginTime,endTime);
			}
            //获取当前分页的值
            List<FillingCardRecharge> fillingCardRechargeList = pb.getBeanList();
			//合计信息总条数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//把数据传到页面
			request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);        
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);
            request.setAttribute("fdescription", fdescription);
            request.setAttribute("fillingCardRechargeList", fillingCardRechargeList);
            request.setAttribute("pb", pb);
            request.setAttribute("type",type);
			request.setAttribute("selectState",selectState);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }        
		return "backHome/carManagement/fillingCardRecharge/fillingCardRechargeList";
	}
	
	/**
	 * 跳转到添加加油卡充值页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoAddFillingCardRecharge")
	public String intoAddFillingCardRecharge(HttpServletRequest request,String type)throws Exception{
		User user = (User)request.getSession().getAttribute("user");
	    //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	    //获取其最大编号
		/*String number = fillingCardRechargeService.selectFnumber(user.getFcompanyid());*/
	    //根据上一个编码获取编码
		String fnumber = GetFnumber.fnumbers("JYKCZ");
	    //获得弹框的里面加油卡的数据
	    //根据公司id和名称查询
		List<FillingCard> fillingCardList = fillingCardService.selectFillingCardByfnameL2(user.getFcompanyid(), null);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
		request.setAttribute("department", department);
	    request.setAttribute("fnumber", fnumber);
		request.setAttribute("user", user);
	    request.setAttribute("fillingCardList", fillingCardList);
	    request.setAttribute("falg",type);
	    request.setAttribute("time",time);
		return "backHome/carManagement/fillingCardRecharge/addFillingCardRecharge";
	}
	/**
	 * 添加加油卡充值
	 * @param request
	 * @param fillingCardRecharge
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addFillingCardRecharge")
	public String addFillingCardRecharge(HttpServletRequest request,FillingCardRecharge fillingCardRecharge)throws Exception{
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    //利用UUID生成fid
	    fillingCardRecharge.setFid(GetFid.UUIDIntoFid());
	    //公司id
	    fillingCardRecharge.setCfficompanyid(user.getFcompanyid());
		//控制单元id
	    fillingCardRecharge.setFcontrolunitid(user.getFcompanyid());
		//创建人id
	    fillingCardRecharge.setFcreatorid(user.getFid());
	    //获取当前时间
	  	String createTime = TimeFormat.timeFormat(new Date());
	  	fillingCardRecharge.setFcreatetime(createTime);
	  	//添加
	  	int row =fillingCardRechargeService.addFillingCardRecharge(fillingCardRecharge);
	  	String result="";
	  	if(row >0){
			result ="1";
		}
	  	//添加日志
        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "加油卡充值进行添加", null, user.getFid());
		return "redirect:/DrivingSys/intoAddFillingCardRecharge?type="+result;
	}
	/**
	 * 跳转到修改加油卡充值页面
	 * @param request
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoUpdateFillingCardRecharge")
	public String intoUpdateFillingCardRecharge(HttpServletRequest request,String fid)throws Exception{
		User user = (User)request.getSession().getAttribute("user");
	    //获取组织
	    Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	    //根据fid查找加油卡充值信息
	    FillingCardRecharge fillingCardRecharge = fillingCardRechargeService.selFillingCardRechargeByFid(fid);
	    //根据公司id和名称查询
	  	List<FillingCard> fillingCardList = fillingCardService.selectFillingCardByfnameL2(user.getFcompanyid(), null);	
	    request.setAttribute("departmentService", departmentService);
	    request.setAttribute("fillingCardRecharge", fillingCardRecharge);
	    request.setAttribute("department", department);
	    request.setAttribute("fillingCardList", fillingCardList);
		return "backHome/carManagement/fillingCardRecharge/updateFillingCardRecharge";
	}
	/**
	 * 修改加油卡充值信息
	 * @param request
	 * @param fillingCardRecharge
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updateFillingCardRecharge")
	public String updateFillingCardRecharge(HttpServletRequest request,FillingCardRecharge fillingCardRecharge)throws Exception{
		//获取操作人信息
	    User user = (User)request.getSession().getAttribute("user");
	    //获取当前时间
	  	String updateTime = TimeFormat.timeFormat(new Date());
	  	//修改人
	  	fillingCardRecharge.setFlastupdateuserid(user.getFid());
	  	//修改时间
	  	fillingCardRecharge.setFlastupdatetime(updateTime);
	  	/*if(fillingCardRecharge.getCfbillstate() == 5L){
	  		//审计id
	  		fillingCardRecharge.setFauditorid(user.getFid());
	  	}*/
	  	//修改
	  	int row = fillingCardRechargeService.updateFillingCardRecharge(fillingCardRecharge);
	  	String result ="";
	  	if(row > 0){
	  		result ="1";
		}
	  	//添加日志
        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "加油卡充值进行修改", null, user.getFid());
		return "redirect:/DrivingSys/queryFillingCardRecharge/look.action?type="+result;
	}
	
	/**
	 * 根据fid删除加油卡充值
	 * @param request
	 * @param deleteId
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteFillingCardRechargeByFid")
	public String deleteFillingCardRechargeByFid(HttpServletRequest request, String[] deleteId,String fid)throws Exception{
		User user = (User) request.getSession().getAttribute("user");
        //删除记录
		if(fid==null || fid.equals("")){
			for (int i = 0; i < deleteId.length; i++) {
	            /*过滤为空的删除操作*/
	            if (!deleteId[i].equals("") && deleteId[i]!=null) {
	            	//根据fid查找单据编号
					FillingCardRecharge fillingCardRecharge = fillingCardRechargeService.selFillingCardRechargeByFid(deleteId[i]);
					activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,fillingCardRecharge.getFnumber());
	            	fillingCardRechargeService.deleteFillingCardRechargeByFid(deleteId[i]);
	            }
	        }	
		}else{
			//根据fid查找单据编号
			FillingCardRecharge fillingCardRecharge = fillingCardRechargeService.selFillingCardRechargeByFid(fid);
			activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,fillingCardRecharge.getFnumber());
			fillingCardRechargeService.deleteFillingCardRechargeByFid(fid);
        }
		//添加日志
        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "加油卡充值进行删除", null, user.getFid());
		return "redirect:/DrivingSys/queryFillingCardRecharge/look.action";
	}
	
	/**
	 * 根据公司id和名称查询 加油卡
	 * @param request
	 * @param fnameL2
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/selFilingCardByName")
	@ResponseBody
	public Object selFilingCardByName(HttpServletRequest request,String fnameL2)throws Exception{
		//获取当前操作人
		User user = (User)request.getSession().getAttribute("user");
		if(!fnameL2.equals("")){
			fnameL2.trim();//去空格			
		}else{
			fnameL2 = null;
		}
		List<FillingCard> fillingCardList = fillingCardService.selectFillingCardByfnameL2(user.getFcompanyid(),fnameL2);
		return fillingCardList;
	}

	/**
	 * 提交单据
	 * @param fid
	 * @param request
	 * @param fnumber
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "submitFillingCardRechargeActiviti")
	@ResponseBody
	public Object submitFillingCardRechargeActiviti(String fid, HttpServletRequest request, String fnumber)throws  Exception{
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		FillingCardRecharge fillingCardRecharge =new FillingCardRecharge();
		fillingCardRecharge.setFid(fid);
		fillingCardRecharge.setCfbillstate(4L);
		fillingCardRecharge.setFlastupdateuserid(user.getFid());
		//创建流程
		axamine.submissionProcess(fnumber);
		int row=fillingCardRechargeService.updateFillingCardRecharge(fillingCardRecharge);
		String result="failed";
		if(row >0){
			result="success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 审核单据
	 * @param request
	 * @param fid
	 * @param agree
	 * @param auditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkFillingCardRechargeActiviti")
	@ResponseBody
	public Object checkFillingCardRechargeActiviti(HttpServletRequest request,String fnumber,String fid,String agree,String auditcomment)throws  Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		FillingCardRecharge fillingCardRecharge =new FillingCardRecharge();
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
		String result ="failed";
		int row1=0;
		if(agree.equals("1")){//同意
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() == 1){//结束
				fillingCardRecharge.setFid(fid);
				fillingCardRecharge.setCfbillstate(5L);
				fillingCardRecharge.setFlastupdateuserid(user.getFid());
				fillingCardRecharge.setFauditorid(user.getFid());
				row1 = fillingCardRechargeService.updateFillingCardRecharge(fillingCardRecharge);
				if(row1 >0 ){//修改单据
					result = "success";
				}
			}else if(serverResponse.getStatus() == 2){
				result = "success";
			}else{

			}
		}else{
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() ==2){
				fillingCardRecharge.setFid(fid);
				fillingCardRecharge.setCfbillstate(3L);
				fillingCardRecharge.setFlastupdateuserid(user.getFid());
				fillingCardRecharge.setFauditorid(user.getFid());
				//修改父类
				row1 =fillingCardRechargeService.updateFillingCardRecharge(fillingCardRecharge);
				if(row1 >0){
					result = "success";
				}
			}
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 反审核单据
	 * @param request
	 * @param fid
	 * @param againstAuditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "againstCheckFillingCardRechargeActiviti")
	@ResponseBody
	public Object againstFillingCardRechargeActiviti(HttpServletRequest request,String fid,String fnumber,String againstAuditcomment )throws  Exception{
		//获取当前登录用户的信息
		User user =(User)request.getSession().getAttribute("user");
		String result ="falied";
		//将单据状态修改成保存状态3
		FillingCardRecharge fillingCardRecharge = new FillingCardRecharge();
		fillingCardRecharge.setFid(fid);
		fillingCardRecharge.setCfbillstate(3L);//保存状态
		fillingCardRecharge.setFauditorid(user.getFid());//设置反审计人id
		int row = fillingCardRechargeService.updateFillingCardRecharge(fillingCardRecharge);
		axamine.againstAuditProcess(fnumber,againstAuditcomment);
		if (row > 0) {
			result = "success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	
	@SuppressWarnings("unchecked")
    /**
     * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
     * @return 返回PageBean实体类
     * @throws Exception
     */
    public PageBean<FillingCardRecharge> getPageBean(HttpServletRequest request, String companyId, String fnumber,
            String fdescription,String beginTime, String endTime) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
		psql.append(" SELECT F.FCREATORID,F.FCREATETIME,F.FLASTUPDATEUSERID,F.FLASTUPDATETIME,F.FCONTROLUNITID,F.FNUMBER,"
			    +" to_char(F.FBIZDATE,'YYYY-MM-DD') FBIZDATE,F.FHANDLERID,F.FDESCRIPTION,F.FHASEFFECTED,F.FAUDITORID,F.FSOURCEBILLID,F.FSOURCEFUNCTION,"
			    +" F.FID,F.FFIVOUCHERED,F.CFFICOMPANYID,F.CFAMOUNT,F.CFBILLSTATE,F.CFREFUELID,"
				+ " E.NAME AS checkName,U.NAME AS createName, F1.FNAME_L2 AS cfrefuelName "
				+ "FROM CT_DS_FILLINGCARDRECHARGE F LEFT JOIN T_E_USER U ON U.FID=F.FCREATORID LEFT JOIN T_E_USER E ON E.FID=F.FAUDITORID "
				+" LEFT JOIN CT_DS_FILLINGCARD F1 ON F1.FID=F.CFREFUELID "
				+ " WHERE F.FCONTROLUNITID='" + companyId + "'");
		if (fnumber == null || fnumber.equals("")) {

		} else {
			psql.append("AND F.FNUMBER LIKE '%" + fnumber + "%' ");
		}
		if (fdescription == null || fdescription.equals("")) {

		} else {
			psql.append("AND F.FDESCRIPTION LIKE '%" + fdescription + "%'");
		}
		if (beginTime == null || endTime == null) {
		/*	beginTime = TimeFormat.getMonth();
		} else if (endTime == null || endTime.equals("")) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			endTime = sdf.format(new Date());
			psql.append("AND TO_CHAR(F.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'");*/
		} else {
			psql.append("AND TO_CHAR(F.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'");
		}

		psql.append(" ORDER BY F.FBIZDATE DESC");
		//System.out.println(psql);
        int psize = 100; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = fillingCardRechargeService.selectPage(pindex, psql.toString(), psize);
        PageBean<FillingCardRecharge> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<FillingCardRecharge>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }
	
	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=fillingCardRechargeService.selectPageCount(psql);
		return paramMap;
	}

	/**
	 * 加油卡充值 导出excel
	 * @param response
	 * @param request
	 * @param fnumber
	 * @param fdescription
	 * @param beginTime
	 * @param endTime
	 */
	@RequestMapping(value ="/importFillingCardRecharge")
	public void importFillingCardRecharge(HttpServletResponse response, HttpServletRequest request
			, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
			, @RequestParam(value = "fdescription", defaultValue = "") String fdescription
			, @RequestParam(value = "beginTime", defaultValue = "") String beginTime
			, @RequestParam(value = "endTime", defaultValue = "") String endTime){
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//定义接收类型
		List<Object> data = new ArrayList<>();
		//查询数据
		List<FillingCardRecharge> fillingCardRecharges=fillingCardRechargeService.selectFillingCardRecharge(user.getFcompanyid(),fnumber,fdescription,beginTime,endTime);
		for (FillingCardRecharge fillingCardRecharge :fillingCardRecharges){
			data.add(fillingCardRecharge.getFnumber());
			data.add(fillingCardRecharge.getFbizdate());
			data.add(fillingCardRecharge.getFdescription());
			data.add(fillingCardRecharge.getCheckName());
			data.add(fillingCardRecharge.getCreateName());
			if (fillingCardRecharge.getCfbillstate() == 3L) {
				data.add("保存");
			} else if (fillingCardRecharge.getCfbillstate() == 4L) {
				data.add("提交");
			} else {
				data.add("审核");
			}
			data.add(fillingCardRecharge.getCfrefuelName());
			data.add(fillingCardRecharge.getCfamount());
		}
		//头部数据
		String head[] = {"单据编号", "业务日期", "参考信息", "审核人名称", "制单人名称", "单据状态", "加油卡", "金额"};
		//长度
		Integer length[] = {9000, 5000, 5000, 3000, 3000, 3000, 3000, 3000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "加油卡充值" + TimeFormat.getNowTime2() + ".xls", "加油卡充值", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
